import express from 'express';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import path from'path';
import userRouter from'./user.js';
import csshook from 'css-modules-require-hook/preset';
import assethook from 'asset-require-hook';
assethook({
	extensions:['svg','png','jpg']
});
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {createStore,applyMiddleware,compose} from 'redux';
import thunk from 'redux-thunk';
import {Provider} from 'react-redux';
import {StaticRouter} from 'react-router-dom';
import reducers from  '../src/reducers'
import App from '../src/App';
import staticPath from '../build/asset-manifest.json';


const Chat = require('./model').getModel('chat');
const app = express();
//为了让socket工作在express上
const server = require('http').Server(app);
const io = require('socket.io')(server);
//ssr首屏渲染
const ssr = req => {
	const store = createStore(reducers,compose(
		applyMiddleware(thunk)
	));
	let context = {};
	const markUp = ReactDOMServer.renderToString(
		(<Provider store={store}>
			<StaticRouter
				location={req.url}
				context={context}
			>
				<App />
			</StaticRouter>
		</Provider>)
	
	);
	
	const pageHtml = `
		<!DOCTYPE html>
		<html lang="en">
		<head>
			<meta charset="utf-8">
			<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
			<meta name="theme-color" content="#000000">
			<meta name="keywords" content="react,学习" />
			<title>React App</title>
			<link rel="stylesheet" type="text/css" href="${staticPath['main.css']}"/>
		</head>
		<body>
		<noscript>
			You need to enable JavaScript to run this app.
		</noscript>
			<div id="root">
				${markUp}
			</div>
		</body>
		<script src="${staticPath['main.js']}" type="text/javascript" charset="utf-8"></script>
		</html>
	`;
	return pageHtml;
}


app.use(cookieParser());
app.use(bodyParser.json());
app.use('/',express.static(path.resolve('build')));
//过滤路由
app.use(function(req,res,next){
	if (req.url.startsWith('/user/') || req.url.startsWith('/static/')) {
		return next();
	}
	
	return res.send(ssr(req));
});
app.use('/user',userRouter);


io.on('connection',function(socket){
	console.log('io has been connect');
	socket.on('sendmsg',function(data){
		console.log(data);
		const {from,to,content} = data;
		const chatid = [from,to].sort().join('_');
		
		Chat.create({from,to,content,chatid},function(err,doc){
			if (err) {
				return res.json({code:1,msg:'后端出错了'});
			}
			//全局事件
			io.emit('recvmsg',doc);
		})
	});
});


server.listen(9093,function(){
	console.log('app server start at port 9093');
});